import { createApp, h, nextTick, ref, type Component } from "vue";
import BasePop from "~/components/BasePop.vue";
import type { BasePopProps } from '~/types/types';

export function usePop(component: Component, propsOrFn: any, modalProps: BasePopProps = {}) {
    const nuxtApp = useNuxtApp()
    const i18n = nuxtApp.$i18n;
    const show = ref(false)
    let app: ReturnType<typeof createApp> | null = null
    let container: HTMLDivElement | null = null
    let isMounted = false

    // 创建 ref 存储组件实例
    const compRef = ref<any>(null)
    const close = (destroy = false) => {
        show.value = false
        // 在关闭时获取组件B的数据并传递给回调
        modalProps?.closeCb?.()

        if (destroy && isMounted) {
            nextTick(() => {
                app?.unmount()
                if (container) {
                    document.body.removeChild(container)
                }
                isMounted = false
                app = null
                container = null
            })
        }
    }

    const open = () => {
        const dynamicProps = ref(
            typeof propsOrFn === 'function' ? propsOrFn() : propsOrFn
        )
        if (!isMounted) {
            const dialog = {
                setup() {
                    provide('i18n', i18n);
                    return () =>
                        h(
                            BasePop,
                            { ...modalProps, show: show.value, onClose: () => close(false) },
                            {
                                default: () => h(component, {
                                    ...dynamicProps.value,
                                    ref: (el: ComponentPublicInstance | null) => {
                                        compRef.value = el
                                    }
                                })
                            }
                        );
                }
            };
            app = createApp(dialog)
            app.config.globalProperties.$t = i18n.t;

            container = document.createElement("div")
            document.body.appendChild(container)
            app.mount(container)
            isMounted = true
        }
        show.value = true
    }

    const unmount = () => close(true)

    return {
        open,
        close,
        unmount,
        compRef
    }
}
